<template>
  <div class="data">
    <div class="head" :style="{ 'background-color': state.type === 'expense' ? '#37a762' : '#f2b63b' }">
      <div class="title">
        <div class="date" @click="() => { show = true }">{{ currentDate[0] }}年{{ currentDate[1] }}月 <van-icon
            name="calendar-o" /></div>
        <div class="type">
          <span :class="{ 'active': state.type === 'expense' }" @click="expenseType(currentDate)">支出</span>
          <span :class="{ 'active': state.type === 'income' }" @click="incomeType(currentDate)">入账</span>
        </div>
      </div>
      <div class="total">
        <p class="title">{{ state.type === 'expense' ? '总支出' : '总收入' }}</p>
        <p class="num">¥{{ state.type === 'expense' ? state.totalExpense : state.totalIncome }}</p>
      </div>
    </div>
    <div class="content">
      <div class="structure">
        <p class="title">{{ state.type === 'expense' ? '支出构成' : '入账构成' }}</p>
        <div class="echarts" ref="echartsRef"></div>
      </div>
    </div>
  </div>
  <van-popup v-model:show="show" position="bottom" :style="{ height: '60%' }">
    <van-date-picker v-model="currentDate" title="选择年月" :min-date="new Date(2020, 1)" :max-date="new Date()"
      :columns-type="columnsType" @confirm="selectDate(currentDate)" />

  </van-popup>

</template>

<script setup>
import { onMounted, ref, reactive } from 'vue'
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import axios from '@/api/index.js';
import formateDate from '@/utils/Date.js';

echarts.use([
  PieChart,
  CanvasRenderer
]);

const echartsRef = ref(null)

onMounted(() => {
  // 获取数据
  getData(formateDate(new Date()).slice(0, -1).join('-'))
})

const state = reactive({
  totalExpense: 0,
  totalIncome: 0,
  expenseList: [],
  incomeList: [],
  type: 'expense'
})
const show = ref(false)
const currentDate = ref(['2025', '01']);
const columnsType = ['year', 'month'];
const date = ref('')

const selectDate = (currentDate) => {
  // 获取数据
  // console.log(currentDate);
  // console.log(`${currentDate[0]}-${currentDate[1]}`);
  date.value = `${currentDate[0]}-${currentDate[1]}`
  // console.log(date.value);
  getData(date.value)
  show.value = false
}

const incomeType = (currentDate) => {
  state.type = 'income'
  // console.log(111);
  date.value = `${currentDate[0]}-${currentDate[1]}`
  getData(date.value)
}

const expenseType = (currentDate) => {
  state.type = 'expense'
  date.value = `${currentDate[0]}-${currentDate[1]}`
  getData(date.value)
}



const getData = async (date) => {
  const res = await axios.get(`api/bill/data?date=${date}`);
  // console.log(formateDate(new Date()).slice(0, -1).join('-'));
  console.log(res);

  // console.log(res);
  state.totalExpense = res.data.total_expense;
  state.totalIncome = res.data.total_income;
  state.expenseList = res.data.total_data.filter(item => item.pay_type === 1)
  state.incomeList = res.data.total_data.filter(item => item.pay_type === 2)

  // console.log(state.expenseList);
  const data = []
  if (state.type === 'expense') {
    state.expenseList.forEach(item => {
      data.push({
        value: item.number,
        name: `${item.type_name} ${(item.number / state.totalExpense * 100).toFixed(2)}%`,
      })
    })
  } else {
    state.incomeList.forEach(item => {
      data.push({
        value: item.number,
        name: `${item.type_name} ${(item.number / state.totalIncome * 100).toFixed(2)}%`,
      })
    })
  }
  data.sort((a, b) => b.value - a.value)
  loadPie(data)
}

const loadPie = (data) => {
  // 加载图表
  const myChart = echarts.init(echartsRef.value);
  const option = {
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          color: (obj) => {
            let len = data.length
            if (state.type === 'expense') {
              return `rgba(54,169,98,${(len + 3 - obj.dataIndex) / (len + 3).toFixed(1)})`
            } else {
              return `rgba(242,182,59,${(len + 3 - obj.dataIndex) / (len + 3).toFixed(1)})`
            }
          },
          borderRadius: 4,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
        },
        labelLine: {
          show: true,
          lineStyle: {
            color: '#666',
          }
        },
        data: data || [
          { value: 1048, name: 'Search Engine' },
          { value: 735, name: 'Direct' },
          { value: 580, name: 'Email' },
          { value: 484, name: 'Union Ads' },
          { value: 300, name: 'Video Ads' }
        ]
      }
    ]
  };
  myChart.setOption(option);
}

</script>

<style lang="less" scoped>
.data {
  .head {
    padding: 50px 20px;
    color: #fff;
    font-size: 16px;
    font-weight: 300;

    .title {
      display: flex;
      justify-content: space-between;

      .type {
        span {
          margin-left: 10px;
          padding: 5px 10px;
          border-radius: 5px;
        }

        span.active {
          background-color: rgba(255, 255, 255, 0.2);
        }

      }
    }

    .total {
      margin-top: 30px;

      .title {
        font-weight: 100;
      }

      .num {
        font-size: 30px;
        font-weight: 500;
        margin-top: 20px;
      }
    }
  }

  .content {
    padding: 30px 20px;

    .structure {
      .title {
        font-size: 16px;
      }

      .echarts {
        width: 100%;
        height: 200px;
        margin-top: 20px;
      }
    }
  }
}
</style>